package com.tron.sync.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "服务监控")
@RestController
public class AppInfoController {

    RestTemplate restTemplate = new RestTemplate();

    @Value("${eureka.client.serviceUrl.defaultZone}")
    String eurekaUrl;

    @GetMapping("/getApps")
    public Object getApps() {
        final HashMap<String, Object> result = new HashMap<>();
        final HashMap<String, Object> dataResult = new HashMap<>();
        final String hostUrl = eurekaUrl.split(",")[0];
        final String forObject = restTemplate.getForObject(hostUrl+"apps", String.class);
        final JSONObject jsonObject = JSONObject.parseObject(forObject);
        final JSONObject applications = jsonObject.getJSONObject("applications");
        final JSONArray application = applications.getJSONArray("application");
        final ArrayList<Map<String, Object>> apps = new ArrayList<>();
        application.forEach(app->{
            final HashMap<String, Object> hashMap = new HashMap<>();
            JSONObject server = (JSONObject) app;
            // 服务名称
            hashMap.put("name", server.getString("name"));
            // 服务对应实例
            final JSONArray instance = server.getJSONArray("instance");
            final ArrayList<Map<String, Object>> insMaps = new ArrayList<>();
            instance.forEach(i->{
                final HashMap<String, Object> insMap = new HashMap<>();
                JSONObject jb = (JSONObject) i;
                // 状态
                insMap.put("status", jb.getString("status"));
                // ip地址
                insMap.put("hostName", jb.getString("hostName"));
                insMaps.add(insMap);
            });
            hashMap.put("instances", insMaps);
            apps.add(hashMap);
        });
        dataResult.put("data",apps);
        result.put("state", 200);
        result.put("message", "success");
        result.put("data",dataResult );
        return result;
    }
}
